package com.jf3q.admin.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jf3q.admin.excel.SubjectData;
import com.jf3q.admin.service.SubjectService;
import com.jf3q.common.domain.EduSubject;
import com.jf3q.common.mapper.EduSubjectMapper;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class SubjectServiceImpl extends ServiceImpl<EduSubjectMapper, EduSubject>
        implements SubjectService {

    public void saveFromExcel(List<SubjectData> cachedDataList) {

        if (ObjectUtils.isEmpty(cachedDataList)) {
            throw new RuntimeException("文件数据为空");
        }
        Map<String, List<String>> map = new HashMap<>();
        for (SubjectData subjectData : cachedDataList) {
            List<String> li = map.get(subjectData.getOne());
            if (li == null) li = new ArrayList<>();
            li.add(subjectData.getTwo());
            map.put(subjectData.getOne(), li);
        }
        List<EduSubject> subjects = this.list();
        Map<String, EduSubject> existMap = new HashMap<>();
        for (EduSubject o : subjects) {
            existMap.put(o.getTitle(), o);
        }
        map.forEach((one, twoLi) -> {
            EduSubject existOneSubject = existMap.get(one);
            if (existOneSubject == null) {
                existOneSubject = new EduSubject();
                existOneSubject.setTitle(one);
                existOneSubject.setParentId("0");
                this.save(existOneSubject);
            }
            List<EduSubject> twoSubjects = new ArrayList<>();
            for (String title : twoLi) {
                EduSubject existTwoSubject = existMap.get(title);
                if (existTwoSubject == null) { //判断二级目录去重
                    existTwoSubject = new EduSubject();
                    existTwoSubject.setTitle(title);
                    existTwoSubject.setParentId(existOneSubject.getId());
                    twoSubjects.add(existTwoSubject);
                }
            }
            //批量保存二级目录
            this.saveBatch(twoSubjects);
        });
    }

}




